<script setup lang="ts">
import { ref, watch, watchEffect, onUnmounted } from 'vue'

// watch 示例
const id = ref(1)
const data = ref<any>(null)
const loading = ref(false)

// 监听 id 变化，拉取新数据
watch(id, async (newId, oldId) => {
  console.log(`ID 从 ${oldId} → ${newId}`)
  loading.value = true
  try {
    // 模拟API调用，因为实际API可能不可用
    // const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${newId}`)
    // data.value = await res.json()
    
    // 使用模拟数据
    setTimeout(() => {
      data.value = {
        id: newId,
        title: `任务 #${newId}: 学习Vue3响应式API`,
        completed: newId % 2 === 0
      }
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取数据失败:', error)
    loading.value = false
  }
}, { immediate: true })

const changeId = () => {
  id.value = Math.floor(Math.random() * 100) + 1
}

// watchEffect 示例
const x = ref(0)
const y = ref(0)
const lastUpdate = ref<string>('')

// 只要 x 或 y 变，就打印最新坐标
watchEffect(() => {
  lastUpdate.value = new Date().toLocaleTimeString()
  console.log(`角色坐标：(${x.value}, ${y.value})`)
})

const updatePosition = () => {
  x.value = Math.floor(Math.random() * 100)
  y.value = Math.floor(Math.random() * 100)
}

// 鼠标位置监听（作业3的简化版）
const mouseX = ref(0)
const mouseY = ref(0)

const handleMouseMove = (event: MouseEvent) => {
  mouseX.value = event.clientX
  mouseY.value = event.clientY
}

// 组件挂载时添加事件监听
onUnmounted(() => {
  window.removeEventListener('mousemove', handleMouseMove)
})
</script>

<template>
  <div class="card">
    <h2>🌟 关卡 4｜watch & watchEffect：侧效应"侦察兵"</h2>
    
    <div class="watch-container">
      <h3>🎯 watch: 定点监控摄像头</h3>
      <button @click="changeId" :disabled="loading">
        {{ loading ? '加载中...' : `获取随机任务 (当前ID: ${id})` }}
      </button>
      <div v-if="data" class="data-display">
        <p><strong>任务ID:</strong> {{ data.id }}</p>
        <p><strong>任务名称:</strong> {{ data.title }}</p>
        <p><strong>完成状态:</strong> {{ data.completed ? '✅ 已完成' : '❌ 未完成' }}</p>
      </div>
    </div>
    
    <div class="watch-effect-container">
      <h3>🛸 watchEffect: AI巡检无人机</h3>
      <button @click="updatePosition">更新坐标</button>
      <div class="position-display">
        <p>角色坐标：({{ x }}, {{ y }})</p>
        <p>最后更新：{{ lastUpdate }}</p>
      </div>
    </div>
    
    <div class="explanation">
      <h4>📝 学习要点</h4>
      <ul>
        <li><strong>watch:</strong> 精确监听指定数据源，可拿到新旧值</li>
        <li><strong>watchEffect:</strong> 立即运行一次，并收集依赖，适合"自动触发"场景</li>
      </ul>
      <p class="funny">💡 趣味比喻：watch 是"定点监控摄像头"；watchEffect 是"AI 巡检无人机"，飞一圈看到啥就记录啥。</p>
    </div>
  </div>
</template>

<style scoped>
.watch-container,
.watch-effect-container {
  margin: 2em 0;
  padding: 1em;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.data-display,
.position-display {
  margin-top: 1em;
  padding: 1em;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.explanation {
  text-align: left;
  margin-top: 2em;
}

.funny {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 1em;
  border-radius: 8px;
  font-style: italic;
}
</style>